package com.teradyne.merlin2.ui.client;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.PlaceChangeEvent;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.place.shared.PlaceHistoryHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.inject.Inject;
import com.teradyne.merlin2.ui.client.places.HomePlace;
import com.teradyne.merlin2.ui.client.places.OrderListPlace;
import com.teradyne.merlin2.ui.client.views.AppLayout;

public class AppControllerImpl implements AppController {

	private static Logger logger = Logger.getLogger("AppControllerImpl");

	private final PlaceController placeController;
	private final PlaceHistoryHandler placeHistoryHandler;
	private AppLayout appLayout;
	private EventBus eventBus;

	/**
	 * All parameters are injected by GIN
	 * 
	 * @param placeController
	 *            the application's PlaceController
	 * @param eventBus
	 *            the application's EventBus
	 * @param placeHistoryHandler
	 *            the application's PlaceHistoryHandler
	 * @param appLayout
	 *            this is the application's main panel
	 * @param activityManagerInitializer
	 *            unused parameter, it's here just to force GIN's initialization
	 *            of ActivityManagers
	 */
	@Inject
	public AppControllerImpl(PlaceController placeController,
			EventBus eventBus, PlaceHistoryHandler placeHistoryHandler,
			AppLayout appLayout,
			ActivityManagerInitializer activityManagerInitializer) {
		this.placeController = placeController;
		this.placeHistoryHandler = placeHistoryHandler;
		this.appLayout = appLayout;
		this.eventBus = eventBus;
		this.appLayout = appLayout;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void start() {

		initLayout();
		placeHistoryHandler.register(placeController, eventBus,
				new HomePlace());

		RootLayoutPanel.get().add(appLayout.getMainLayoutPanel());
		placeHistoryHandler.handleCurrentHistory();

		eventBus.addHandler(PlaceChangeEvent.TYPE, new PlaceLayoutHandler(
				appLayout));

	}

	// initialize layout based on current token
	private void initLayout() {
		appLayout.setDefaultLayout();

	}

	private void handleError(Throwable caught) {
		Window.alert("There was something wrong with your request.");
		logger.log(Level.SEVERE, caught.getMessage());
	}

}